package cn.lsj.orm;

import cn.lsj.core.factory.SqlSessionFactory;
import cn.lsj.core.factory.SqlSessionFactoryBuilder;
import org.dom4j.DocumentException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;

import java.io.InputStream;

@Configuration
@ConditionalOnClass(value = {SqlSessionFactory.class})
@EnableConfigurationProperties(value = {DataSourceProperties.class})
public class LsjORMConfiguration {

    private final DataSourceProperties dataSourceProperties;

    public LsjORMConfiguration(DataSourceProperties dataSourceProperties) {
        this.dataSourceProperties = dataSourceProperties;
    }

    @Bean
    public cn.lsj.core.entity.Configuration configuration() {
        cn.lsj.core.entity.Configuration configuration = new cn.lsj.core.entity.Configuration();
        configuration.setDriver(dataSourceProperties.getDriver());
        configuration.setPassword(dataSourceProperties.getPassword());
        configuration.setUrl(dataSourceProperties.getUrl());
        configuration.setUsername(dataSourceProperties.getUsername());
        return configuration;
    }

    @Bean
    public SqlSessionFactoryBuilder sqlSessionFactoryBuilder() {
        return new SqlSessionFactoryBuilder();
    }

    @Bean
    @DependsOn(value = "sqlSessionFactoryBuilder")
    @ConditionalOnProperty(name = "lsjorm.frame.enable", havingValue = "true", matchIfMissing = true)
    public SqlSessionFactory sqlSessionFactory(@Autowired SqlSessionFactoryBuilder sqlSessionFactoryBuilder,
                                               @Autowired @Qualifier("configuration") cn.lsj.core.entity.Configuration configuration) {
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("SqlMapConfig.xml");
        try {
            return sqlSessionFactoryBuilder.build(inputStream, configuration);
        } catch (DocumentException e) {
            throw new RuntimeException(e);
        }
    }


}